//
//  ViewController.swift
//  Calculator
//
//  Created by Apple on 2017/12/24.
//  Copyright © 2017年 Apple. All rights reserved.
//

import UIKit


class ViewController: UIViewController {
    @IBOutlet weak var display: UILabel!
    
    //用户是否输入了数字，若输入则直接赋值
    var isInTheMiddle:Bool = false
    
    //是否刚刚计算过
    var isHasEvaluate = false;
    
    //用户输入的数字栈
    var operandStack:Array<Double> = Array<Double>()
    
    //用户输入的操作栈
    var operationStack:Array<String> = Array<String>()
    
    var brain =  CalculatorBrain();
    
    
    @IBAction func appendDigit(_ sender: UIButton) {
        let digit = sender.currentTitle!
        
        if(isInTheMiddle){
            display.text=display.text! + digit
        }else{
            display.text=digit
            isInTheMiddle=true
        }
        
        isHasEvaluate = false;
    }
    
    @IBAction func operate(_ sender: UIButton) {
        let operation=sender.currentTitle!;

        if isInTheMiddle || isHasEvaluate {
            enter()
        }
        
        isHasEvaluate = false;
        
        switch operation {
            case "C":display.text="0";brain.reset();
            case "=":displayValue = brain.evaluate();isHasEvaluate = true;
            default:clickOperation(operation: operation);
        }
    }
    
    //点击加减乘除
    func clickOperation(operation:String){
        if let result = brain.isOperandStackFull (symbol:operation){
            displayValue = result;
        }
        brain.pushOperation(symbol: operation);
    }
    
   
    
    func enter() {
        isInTheMiddle = false
        brain.pushOperand(operand: displayValue)
    }
    
    var displayValue : Double! {
        get{
            if display.text == "错误" {
                display.text = "0";
            }
            return NumberFormatter().number(from: display.text!)!.doubleValue
        }
        
        set{
            if newValue == nil {
                display.text = "错误"
                isInTheMiddle = false
            }else{
                display.text = "\(newValue!)"
                
                //print display.text;
                let tempText = NSString(string:"\(newValue!)")
                if(tempText.hasSuffix(".0")){
                    let tempTextLength=tempText.length-2;
                    display.text=tempText.substring(to: tempTextLength)
                }
                isInTheMiddle = false
            }
        }
    }

}

